/*
 * @Description: 用户详情
 * @Author: fhw
 * @Date: 2022-12-31 21:52:51
 */
import { defineComponent, PropType, computed, reactive, h, onMounted, onUnmounted, ref } from 'vue'
import { IconMale, IconGirl } from '@/components/icon'
import { EllipsisOutlined, UserOutlined } from '@ant-design/icons-vue'
import './index.scss'
import { User } from '@/interface'
import { equals } from 'ramda'
import { isTrue } from '@/utils/tools'
import { MenuItem, UserSetUpMenuItem } from '../interface'
import { configFilter } from '@/dictionaries/filter'
import { BasicDataModule } from '@/store/modules/basicData'

const props = {
	loading: Boolean as PropType<boolean>,
	dataSource: {
		type: Object as PropType<User>,
		required: true,
	},
	menu: {
		type: Array as PropType<Array<MenuItem>>,
		default: [],
	},
	/** 是否显示备注 */
	showRemarks: {
		type: Boolean as PropType<boolean>,
		default: true,
	},
	/** 显示更多 */
	showMore: {
		type: Boolean as PropType<boolean>,
		default: true,
	},
} as const
export default defineComponent({
	props,
	emits: ['update:loading'],
	setup(props) {
		const userRef = ref()
		const userId = localStorage.getItem('userId') as string
		// 好友备注集合
		const friendsRemarksMap = computed<Map<string, string>>(() => {
			return BasicDataModule.friendsRemarksMap
		})
		const isUser = computed(() => equals(Number(userId), props.dataSource?.id as number))
		const pageState = reactive({
			isRemarks: false,
			fromData: {
				remarks: '',
			},
		})
		const userSetUpMenu = reactive<UserSetUpMenuItem[]>([
			{
				title: '备注名',
				hide: !props.showRemarks,
				slots: () => userRemarksRender(),
			},
			{
				title: '来源',
				hide: !isTrue(props.dataSource.source),
				slots: <span style="color: #000">{configFilter('sourceType', props.dataSource.source as number)}</span>,
			},
		])
		function userRemarksRender() {
			return pageState.isRemarks ? (
				<a-input v-model={[pageState.fromData.remarks, 'value']} onBlur={updateRemarks}></a-input>
			) : (
				<span
					onClick={openRemarks}
					style={`cursor: pointer;width: 100%;display: inline-block;color:${
						friendsRemarksMap.value.get(String(props.dataSource?.id)) ? '#000' : '#A2A3A3'
					}`}
				>
					{friendsRemarksMap.value.get(String(props.dataSource?.id)) || '点击添加备注'}
				</span>
			)
		}

		// 更新用户备注
		async function updateRemarks() {
			if (!pageState.fromData.remarks) {
				pageState.isRemarks = false
				return
			}
			const params: API.blog.chatUserFriends.updateRemarks.Params = {
				userId: userId,
				friendsId: props.dataSource.id,
				remarks: pageState.fromData.remarks,
			}
			const { success } = await API.blog.chatUserFriends.updateRemarks.request(params)
			if (success) {
				pageState.isRemarks = false
				const { remarks } = pageState.fromData
				friendsRemarksMap.value.set(String(props.dataSource?.id), remarks)
				pageState.fromData.remarks = ''
			}
		}
		function openRemarks() {
			pageState.isRemarks = !pageState.isRemarks
			pageState.fromData.remarks = friendsRemarksMap.value.get(String(props.dataSource?.id)) as string
		}
		onMounted(() => {
			// 全局点击事件
			document.addEventListener('mouseup', onMouseup, false)
		})
		onUnmounted(() => {
			document.removeEventListener('mouseup', onMouseup, false)
		})
		function onMouseup(e: any) {
			if (userRef.value) {
				// 判断鼠标点击的区域是否在tree里面，否则关闭弹窗
				if (!userRef.value.contains(e.target) && !props.loading) {
					pageState.isRemarks = false
				} else {
					return
				}
			}
		}
		return () => (
			<div class="userInfo" ref={userRef}>
				{props.loading ? (
					<div style="height: 100px;display: flex;justify-content: center;align-items: center;">
						<a-spin size="large" />
					</div>
				) : (
					<>
						<div class="user-details" style={{ borderBottom: props.showRemarks ? '1px solid #e9e9e9' : 'none' }}>
							<div class="user-img">
								{isTrue(props.dataSource?.headimgurl) ? (
									<img src={props.dataSource?.headimgurl} alt="" />
								) : (
									<a-avatar shape="square" size={70} icon={<UserOutlined />} />
								)}
							</div>
							<div class="user-info-box">
								<p class="nickname">
									<p>
										{friendsRemarksMap.value.get(String(props.dataSource?.id)) || props.dataSource?.username}&nbsp;
										{equals(props.dataSource?.sex, '男') ? (
											<IconMale fontSize={18} style="margin-left: 4px" />
										) : (
											<IconGirl fontSize={18} style="margin-left: 4px" />
										)}
									</p>
									{props.showMore && <EllipsisOutlined style={{ fontSize: '26px', color: '#808080' }} />}
								</p>
								<p class="username">
									昵称：<span>{props.dataSource?.username}</span>
								</p>
								<p class="account">
									账号：<span>{props.dataSource?.account}</span>
								</p>
							</div>
						</div>
						<ul class="user-setUp">
							{!isUser.value &&
								userSetUpMenu
									.filter((item) => !item.hide)
									.map((item) => (
										<li class="userSetUpMenuItem">
											<p>{item.title}</p>
											<p>{h(item.slots)}</p>
										</li>
									))}
						</ul>
						{isTrue(props.menu) && (
							<ul class="menu-box">
								{props.menu
									?.filter((item) => !item.hide)
									.map((item) => {
										return (
											<li class="btn-box">
												{isTrue(item.slots) ? (
													h(item.slots as object)
												) : (
													<a-button
														type="primary"
														disable={item.disable}
														onClick={() => {
															item.handler && item.handler()
														}}
													>
														{item.text}
													</a-button>
												)}
											</li>
										)
									})}
							</ul>
						)}
					</>
				)}
			</div>
		)
	},
})
